import time

from Autotests.LocalMachine.Controls.Label import WebLabel
from Autotests.LocalMachine.Controls.Button import WebButton
from Autotests.LocalMachine.Controls.ProgressBar import BackupRestoreProgressBar
from Autotests.LocalMachine.Controls.TreeView import WebTreeView
from Autotests.LocalMachine.Controls.TableView import WebTableView, WebTableViewDelegateBuilder
from Autotests.LocalMachine.Controls.ComboBox import WebComboBox
from Autotests.LocalMachine.Controls.CheckBox import WebDefaultCheckBox
from Autotests.LocalMachine.Controls.LineEdit import WebLineEdit
from Autotests.LocalMachine.Controls.ListView import WebListView, WebListViewDelegateBuilder
from Autotests.LocalMachine.Controls.BaseView import BaseWebViewLeafDelegate
from Autotests.LocalMachine.Controls.BaseControl import WebFindKey, BaseWebControl
from Autotests.LocalMachine.Pages.BasePage import BaseWebPage
from Autotests.LocalMachine.UiObjectsMap.AirClient import Restore as RestoreUi, MainFrame as MainFrameUi
from Autotests.LocalMachine.Pages.BaseDialog import BaseWebTreeDialog


class WebRestorePage(BaseWebPage):
    def __init__(self):
        super(WebRestorePage, self).__init__(RestoreUi.restorePage)
        self._restoreProgressBar = BackupRestoreProgressBar()
        self._restoreTree = WebTreeView(RestoreUi.restoreTreeView)
        self._pluginComboBox = WebComboBox(RestoreUi.pluginComboBox)
        self._sessionComboBox = WebComboBox(RestoreUi.sessionComboBox)
        self._startRestoreButton = WebButton(RestoreUi.btnStartRestore)
        self._restoreToPathTree = BaseWebTreeDialog()
        self._restoreToOriginLocRadioButton = WebDefaultCheckBox(RestoreUi.radioBtnRestoreToOriginalLoc)
        self._restoreToPathRadioButton = WebDefaultCheckBox(RestoreUi.radioBtnRestoreToPath)
        self._restoreToPathEdit = WebLineEdit(RestoreUi.txtRestoreToPath)
        self._searchEdit = WebLineEdit(RestoreUi.txtSearch)
        #self._searchResultTable = WebTableView(RestoreUi.searchResultTable)

    def goToHomeLocation(self):
        super(WebRestorePage, self).goToHomeLocation()
        WebButton(MainFrameUi.btnRestore).click()

    def waitForRestoreComplete(self, timeout=20 * 60):
        self._restoreProgressBar.waitForComplete(timeout, message="Restore perform timeout")

    @BaseWebPage.setter
    def makeSelection(self, path, plugin, session):
        self._restoreTree.deselectAll()
        self._restoreTree.setItemSelection(path, True)
        self._pluginComboBox.selectItemsByDataValue(plugin)
        if session:
            self._sessionComboBox.selectItem(session)

    def selectRestorePath(self, path):
        self._restoreToPathRadioButton.setCheckState(True)
        self._restoreToPathEdit.click()
        self._restoreToPathTree.setItemSelection(path)

    def startRestore(self, path, plugin, session = None, restoreToPath = None):
        self.makeSelection(path, plugin, session)
        if restoreToPath:
            self.selectRestorePath(restoreToPath)
        time.sleep(5)  # wait button update
        self._startRestoreButton.click()

    def performRestore(self, path, plugin, session = None, restoreToPath = None, timeout=20 * 60):
        self.startRestore(path, plugin, session, restoreToPath)
        self.waitForRestoreComplete(timeout)


    def performSearch(self, searchValue):
        self.goToHomeLocation()
        self._searchEdit.typeText(searchValue)
        self._searchEdit.submit()
        self._searchResultListBuilder = WebListViewDelegateBuilder(RestoreUi.ListSearchResultItem.listItem,
                                                         WebSearchResultListDelegate)
        self._searchResultList = WebListView(RestoreUi.searchResultList, self._searchResultListBuilder)

    def getSearchResultRowCount(self):
        self._searchResultListBuilder = WebListViewDelegateBuilder(RestoreUi.ListSearchResultItem.listItem,
                                                         WebSearchResultListDelegate)
        time.sleep(1)
        return WebListView(RestoreUi.searchResultList, self._searchResultListBuilder).rowsCount()

    def getSearchResultColumn(self, column):
        result = []
        for item in self._searchResultList.items():
            time.sleep(1)
            result.append(item.column(column))
        return result

    def getLastBackupDate(self):
        return WebLabel((WebFindKey.XPATH,
                         '//div[@class="right-sidebar"]/div[@class="status-backup-container"]/a/span/span[2]')).text()

    def _getResultDelegate(self, time):
        items = self._searchResultList.itemsFor(lambda x: x.backupTime() == time)
        return items[0] if items else None

    def findAndRestore(self, fileName, restoreToPath = None, timeout=20 * 60):
        self.performSearch(fileName)
        time.sleep(1)
        resultToRestore = self._getResultDelegate(self.getLastBackupDate())
        if resultToRestore == None:
            raise Exception("No file with latest backup date found. Nothing to restore!")
        resultToRestore.click()
        if restoreToPath:
            self.selectRestorePath(restoreToPath)
        time.sleep(5)  # wait button update
        self._startRestoreButton.click()
        self.waitForRestoreComplete(timeout)


class WebSearchResultListDelegate(BaseWebViewLeafDelegate):
    def __init__(self, handler, index):
        super(WebSearchResultListDelegate, self).__init__(handler, index)
        self._labelFilePath = WebLabel(self.waitChildControl(*RestoreUi.ListSearchResultItem.labelFilePath, timeoutSec=4))
        self._labelBackupTime = WebLabel(self.waitChildControl(*RestoreUi.ListSearchResultItem.labelBackupTime))
        self._labelFileSize = WebLabel(self.waitChildControl(*RestoreUi.ListSearchResultItem.labelFileSize))

    def filePath(self):
        return self._labelFilePath.text()

    def backupTime(self):
        return self._labelBackupTime.text()

    def fileSize(self):
        return self._labelFileSize.text()

    def column(self, index):
        if index == 0:
            return self.filePath()
        elif index == 1:
            return self.backupTime()
        else:
            return self.fileSize()



